#include "usbISR.h"
#include "uart.h"
#include "common.h"
usbEp0OutHandler(usbEnuFsm * usbEnuStatus)
{
	//raiseLevel();
	usb_1362_LockDevice(0xaa37);//0xaa37);
	int i;
	int bufLength;
#if USB_ENU_DEBUG
	uartPrintf("in the ep0 out handler\n");
	printf("in the ep0 out handler\n");
#endif
/*1. read host request*/
	bufLength = usb_1362_device_epx_read(0, usbEnuStatus->rxBuf);
	
	if(usbEnuStatus->ep0Status & 0x04){
	usb_1362_device_0_write(ISP_1363_Acknowledge_Set_Up);//ack the set-up packet
	usb_1362_device_0_write(ISP_1362_EP0_OUT_Clear_Buffer_reg);//clear buffer
	//usbEnuStatus->ep0Status = usb_1362_device_16_read(ISP_1362_DcEndpointStatus_EP0_OUT_Read_reg);	
		}
/*2. check the request*/
	usbEnuStatus->usbRequest = analyseUsbRequest((char*)(usbEnuStatus->rxBuf));
	usbEnuStatus->usbClassRequest =  analyseUsbClassRequest((char*)(usbEnuStatus->rxBuf));
#if USB_ENU_DEBUG
	printf("usbRequest:%d\n usbClassRequest:%d\n",usbEnuStatus->usbRequest,usbEnuStatus->usbClassRequest);
#endif
	if((usbEnuStatus->usbRequest == -1) 
		&& (usbEnuStatus->usbClassRequest == -1)){
					usb_1362_ep0_stall();
			printf("EP0 Stall!\n");
			return;
			}
	else 
		usbEnuStatus->fsmStatus = USB_CONTROL_HANDLE;
		
//	uartPrintf("[uart]usb request:%d\n",usbEnuStatus->usbRequest);
//	printf("[uart]usb request:%d\n",usbEnuStatus->usbRequest);
//	printf("ep0 status:%x\n",usbEnuStatus->ep0Status);
/*3. Do the request*/
	if(usbEnuStatus->fsmStatus == USB_CONTROL_HANDLE){
		if(!(usbEnuStatus->ep0Status & 0x60)){
			printf("EP0: buffer not full. exit....\n");
			usb_1362_epx_transmit(0,NULL,0);
			//usb_1362_device_0_write(ISP_1362_EP0_OUT_Clear_Buffer_reg);//clear buffer
			return;
			}
		else if((usbEnuStatus->ep0Status & 0x04)){        //fifo full  setup packet            
			if(usbEnuStatus->usbRequest != -1)
				doUsbStandardRequest(usbEnuStatus);
			else if(usbEnuStatus->usbClassRequest != -1)
				doUsbClassRequest(usbEnuStatus);
			}
		else{										//no data
			printf("EP0:Do nothing\n");
			}					
	}
}













